package com.example.io;

import org.junit.Test;

import java.io.*;

/**
 * @author readpage
 * @create 2022-10-12 21:22
 *
 * 测试FileInputStream和FileOutputStream
 * 结论:
 * 1. 对于文本文件(.txt,.java,.c,.cpp), 使用字符流处理
 * 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理
 */
public class FileInputOutputStreamTest {

    //使用字节流FileInputStream处理文本文件，可能出现乱码。
    @Test
    public void testFileInputStream() throws IOException {
        FileInputStream fis = null;
        try {
            //1. 创建文件
            File file = new File("hello.txt");

            //2.创建流
            fis = new FileInputStream(file);

            //3.读数据
            //方式一
            byte[] buffer = new byte[5];
            int len;  //记录每次读取的字节的个数
            while ((len = fis.read(buffer)) != -1) {
                String str = new String(buffer, 0, len);
                System.out.print(str);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4.关闭资源
            if (fis != null) {
                fis.close();
            }
        }
    }


    //指定路径下文件的复制
    public void copyFile(String srcPath, String destPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            if (srcFile.exists()) {
                FileUtils.create(srcFile);
            }
            if (destFile.exists()) {
                FileUtils.create(destFile);
            }

            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer = new byte[100];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }

    @Test
    public void testCopyFile() {
        long start = System.currentTimeMillis();

        String srcPath = "E:\\GY_NEW.zip";
        String destPath = "E:\\tmp\\GY_NEW2.zip";
        copyFile(srcPath, destPath);

        long end = System.currentTimeMillis();

        System.out.println("复制操作花费的时间为: " + (end - start));
    }
}
